package controller;

import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;

import application.AlertDialog;
import application.ProgressFrom;
import bean.GoodsDetails;
import bean.TxtContent;
import bean.TxtFile;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TableColumn.CellDataFeatures;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.input.MouseEvent;
import javafx.stage.DirectoryChooser;
import javafx.util.Callback;
import service.MyTask;
import service.TxtService;
import serviceImpl.TxtServiceImpl;
import util.PropertyUtil;

public class ChangeController implements Initializable {

    @FXML
    private CheckBox selectAll;

    @FXML
    private Button txtBtn;
    
    @FXML
    private Button outPutBtn;
    
    @FXML
    private Button xmlBtn;
    
    @FXML
    private TableView<TxtFile> tv_txtFile;
    
    @FXML
    private TableColumn<TxtFile, CheckBox> checkCol;
    
    @FXML
    private TableColumn<TxtFile, String> pathCol;
    
    @FXML
    private TableColumn<GoodsDetails, String> goodsNo;

    @FXML
    private TableColumn<GoodsDetails, String> standard;

    @FXML
    private TableColumn<GoodsDetails, String> taxMon;

    @FXML
    private TableColumn<GoodsDetails, String> tax;
    
    @FXML
    private TableColumn<GoodsDetails, String> sortNo;
    
    @FXML
    private TableColumn<GoodsDetails, String> unit;
    
    @FXML
    private TableColumn<GoodsDetails, String> rate;

    @FXML
    private TableColumn<GoodsDetails, String> noTaxMon;

    @FXML
    private TableView<GoodsDetails> tv_goods;

    @FXML
    private TableColumn<GoodsDetails, String> goodsName;
    
    //保存选择的文档
    private List<String> fileList = new ArrayList<String>();
    
    TxtService txtService = new TxtServiceImpl();
    
    /**
     * 选择txt文件路径
     * @param event
     */
    @FXML
    void selectTxtAction(ActionEvent event) {
		//文件选择框
		DirectoryChooser fileChooser = new DirectoryChooser();
        //获取上次设置的txt路径
        String txtPath = PropertyUtil.getKeyValue("txtPath");
        if(!txtPath.equals("")&&new File(txtPath).exists()){
        	fileChooser.setInitialDirectory(new File(txtPath));
        }
        File file = fileChooser.showDialog(txtBtn.getScene().getWindow());
		//路径回显
        if(file!=null){
        	//将txt文档设置路径存入config文件中
        	PropertyUtil.writeProperties("txtPath", file.getAbsolutePath());
        	//读取当前文件夹下所有txt文件
        	ObservableList<TxtFile> list = configTxtTable(file.getAbsolutePath());
        	tv_txtFile.setItems(list);
        }
    }
    
    /**
     * 指定生成路径
     * @param event
     */
    @FXML
    void outPutPathAction(ActionEvent event){
    	//文件选择框
		DirectoryChooser fileChooser = new DirectoryChooser();
        //获取上次设置的生成路径
        String outPutPath = PropertyUtil.getKeyValue("outPutPath");
        if(!outPutPath.equals("")&&new File(outPutPath).exists()){
        	fileChooser.setInitialDirectory(new File(outPutPath));
        }
        File file = fileChooser.showDialog(outPutBtn.getScene().getWindow());
		//路径回显
        if(file!=null){
        	//将生成路径存入config文件中
        	PropertyUtil.writeProperties("outPutPath", file.getAbsolutePath());
        }
    }
    
    /**
     * 全选checkbox事件监听
     * @param event
     */
    @FXML
    void selectAllAction(ActionEvent event){
    	CheckBox checkBox = (CheckBox) event.getSource();
    	Boolean flag = checkBox.selectedProperty().getValue();

    	ObservableList<TxtFile> list = tv_txtFile.getItems();
    	fileList = new ArrayList<String>();
    	for (TxtFile txtFile : list) {
			txtFile.setIsSelected(flag);
			if(flag){
				fileList.add(txtFile.getTxtPath());
			}else{
				fileList.remove(txtFile.getTxtPath());
			}
		}    	
    	
    	tv_txtFile.setItems(list);
    	tv_txtFile.refresh();
    }
    
    /**
     * 刷新txt文件列表
     * @param event
     */
    @FXML
    void refreshAction(ActionEvent event){
    	String txtPath = PropertyUtil.getProperties("txtPath");
    	//读取当前文件夹下所有txt文件
    	ObservableList<TxtFile> list = configTxtTable(txtPath);
    	tv_txtFile.setItems(list);
    	tv_txtFile.refresh();
    }
    
    /**
     * 生成xml
     * @param event
     */
    @FXML
    void changeToXmlAction(ActionEvent event){
    	String outPutPath = PropertyUtil.getKeyValue("outPutPath");
    	if(!outPutPath.equals("")&&outPutPath != null){
    		MyTask task = new MyTask(fileList);
    		task.valueProperty().addListener(new MyTaskListener());
    		
    		ProgressFrom progressFrom = new ProgressFrom(task,xmlBtn.getScene().getWindow());
    		progressFrom.activateProgressBar();
    	}else{
    		AlertDialog.informationDialog("提示", "请先设置生成路径",xmlBtn.getScene().getWindow());
    	}
    	
    }
    
    class MyTaskListener implements ChangeListener<String> {

		@Override
		public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
			// TODO Auto-generated method stub
    		String txtPath = PropertyUtil.getKeyValue("txtPath");
    		
    		//初始化table
    		ObservableList<TxtFile> list = configTxtTable(txtPath);
    		
    		selectAll.selectedProperty().setValue(false);
    		
    		tv_txtFile.setItems(list);
    		//清空
    		fileList = new ArrayList<String>();
    		
    		AlertDialog.informationDialog("提示", newValue,xmlBtn.getScene().getWindow());
		}
    }
    

	/**
	 * 窗口初始化
	 */
	public void initialize(URL location, ResourceBundle resources) {
		//读取config文件中txtPath
		String txtPath = PropertyUtil.getKeyValue("txtPath");
		
		//初始化table
		ObservableList<TxtFile> list = configTxtTable(txtPath);
		
    
		tv_txtFile.setItems(list);
		
		
		
	}

	/**
	 * 初始化配置tv_txtFile
	 * @return 
	 */
	private ObservableList<TxtFile> configTxtTable(String txtPath) {
		
		pathCol.setCellValueFactory(new PropertyValueFactory<TxtFile, String>("txtPath"));
		pathCol.setCellFactory(new Callback<TableColumn<TxtFile,String>, TableCell<TxtFile,String>>() {
			
			@Override
			public TableCell<TxtFile, String> call(TableColumn<TxtFile, String> param) {
				TextFieldTableCell<TxtFile, String> cell = new TextFieldTableCell<>();
				cell.setOnMouseClicked((MouseEvent event)->{
					//鼠标双击执行操作
					if(event.getClickCount() == 2){
						TableCell<?, ?> c = (TableCell<?, ?>) event.getSource();
						//读取txt文件内容
						TxtContent content = txtService.parseTxt(c.getText());
						if(content.getBz() == null){
							AlertDialog.informationDialog("提示", content.getTxtName()+"文件格式不正确",tv_txtFile.getScene().getWindow());
						}else{
							//初始化tv_goods
							configGoodTable(content);
						}
					}
				});
				return cell;
			}
		});

		
		//设置CheckBox
		//checkCol.setCellValueFactory(cellData ->cellData.getValue().cb.getCheckBox());
		checkCol.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<TxtFile,CheckBox>, ObservableValue<CheckBox>>() {
			
			
			@Override
			public ObservableValue<CheckBox> call(CellDataFeatures<TxtFile, CheckBox> param) {
				
				TxtFile txtfile = param.getValue();
				CheckBox checkBox = new CheckBox();
				checkBox.setSelected(txtfile.getIsSelected());
				//checkBox.selectedProperty().setValue(txtfile.getIsSelected());
				checkBox.selectedProperty().addListener(new ChangeListener<Boolean>() {
					public void changed(ObservableValue<? extends Boolean> ov,
							Boolean old_val, Boolean new_val) {
						checkBox.setAlignment(Pos.CENTER);
						checkBox.setSelected(new_val);
						txtfile.setIsSelected(new_val);
						//判断当前状态是否为选中状态
						if(new_val){
							fileList.add(txtfile.getTxtPath());
						}else{
							fileList.remove(txtfile.getTxtPath());
						}
						
					}
					
				});                
				return new SimpleObjectProperty<CheckBox>(checkBox);
			}
		});
		
		
		//javaFx放置数据集合
		ObservableList<TxtFile> list = FXCollections.observableArrayList();
		List<String> txtNameList = new ArrayList<String>();
		if(!txtPath.equals("")){
			//初始化txt文档列表
			txtNameList = txtService.showTxtList(txtPath);
		}
		for (String txtName : txtNameList) {
			TxtFile txt = new TxtFile();
			txt.setTxtPath(txtName);
			list.add(txt);
		}
		
		return list;
	}
	
	/**
	 * 初始化tv_goods
	 * @param content
	 */
	protected void configGoodTable(TxtContent content) {
		goodsNo.setCellValueFactory(new PropertyValueFactory<>("spCode"));
		goodsName.setCellValueFactory(new PropertyValueFactory<>("spmc"));
		unit.setCellValueFactory(new PropertyValueFactory<>("jldw"));
		standard.setCellValueFactory(new PropertyValueFactory<>("ggxh"));
		taxMon.setCellValueFactory(new PropertyValueFactory<>("mon"));
		noTaxMon.setCellValueFactory(new PropertyValueFactory<>("je"));
		rate.setCellValueFactory(new PropertyValueFactory<>("slv"));
		sortNo.setCellValueFactory(new PropertyValueFactory<>("spbm"));
		
		//javaFx放置数据集合
		ObservableList<GoodsDetails> list = FXCollections.observableArrayList();
		for (GoodsDetails good : content.getGoodsList()) {
			list.add(good);
		}
		
		tv_goods.setItems(list);
	}


}

